<?php
class TbfUpload{
    static function jsonImageUpload(){
        $ret = self::ArrayImageUpload();
        if (!empty($ret['err'])){
            echo json_encode($ret);
        }else{
            echo json_encode(array('err'=>'','data'=>$ret['url']));
        }
    }

    static function hiddenIframeImageUpload(){
        $ret = self::ArrayImageUpload();
        $output = array();
        if (!empty($ret['err'])){
            $output['err'] = $ret['err'];
        }else{
            $output['data'] = $ret['url'];
        }
        echo '<script>var data=';ejson($output);echo ';</script>';
    }

    static function ArrayImageUpload(){
        return self::_arrayUploadInner('image',array('jpg','png','gif','jpeg'));
    }

    static function jsonAttachUpload(){
        $ret = self::_arrayUploadInner('attach',array('doc','docx','xlsx','xls','zip','rar','pdf'));
        if (!empty($ret['err'])){
            echo json_encode($ret);
        }else{
            echo json_encode(array('err'=>'','data'=>$ret['url']));
        }
    }
    static function _arrayUploadInner($name,$extArray){
        //文件路径没有结尾的/
        $saveBasePath = TbfConfig::$UploadPath.'/'.$name;
        if (empty($_FILES['file']['tmp_name'])){
            return array('err'=>'upload file not found');
        }
        @mkdir($saveBasePath);
        $ext = TbfFile::getExtLower($_FILES['file']['name']);
        if (!in_array($ext,$extArray)){
            return array('err'=>'ext not allow.');
        }
        $fileName = md5_file($_FILES['file']['tmp_name']).'.'.$ext;
        $ret = move_uploaded_file($_FILES['file']['tmp_name'],$saveBasePath.'/'.$fileName);
        if (!$ret){
            return array('err'=>'move fail');
        }
        return array('err'=>'','url'=>TbfConfig::$UploadUrlPrefix.'/'.$name.'/'.$fileName);
    }
}